package com.daxilong.starchen.player.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.Toast;
import androidx.annotation.NonNull;

import com.daxilong.starchen.player.R;
import com.daxilong.starchen.player.databinding.ActivityVideoPlayerBinding;
import com.daxilong.starchen.player.model.MediaItem;
import com.daxilong.starchen.player.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class VideoPlayerActivity extends BaseActivity {

    private static final String TAG = "VideoPlayerActivity";

    private static final int PROGRESS = 0;
    //隐藏控制面板
    private static final int HIDE_MEDIACONTROLLER = 2;
    private ActivityVideoPlayerBinding binding;
    private Uri uri;
    private BatteryReceiver batteryReceiver;
    private ArrayList<MediaItem> mediaItems;
    private int position;
    private boolean isShowMediaController = false;
    //默认播放
    private static final int DEFAULT_SCREEN = 3;
    //全屏播放
    private static final int FULL_SCREEN = 4;
    /**
     * 显示网速
     */
    private static final int SHOW_SPEED = 5;
    //屏幕的宽
    private int screenWidth;
    //屏幕的高
    private int screenHeight;
    //视频的本身的宽和高
    private int videoWidth;
    private int videoHeight;
    private AudioManager audioManager;
    //当前的音量：0~15
    private int currentVolume;
    //最大音量
    private int maxVolume;
    //是否是静音
    private boolean isMute = false;
    //是否全屏播放
    private boolean isFullScreen = false;
    private float startX;
    private float startY;
    private float touchRang;
    private int mVol;
    //是否是网络资源
    private boolean isNetUri = false;
    private int prePosition = 0;
    //视频总时长
    int duration;
    //定义手势识别器
    private final GestureDetector detector = new GestureDetector(getApplication(),new GestureDetector.SimpleOnGestureListener(){
        @Override
        public void onLongPress(MotionEvent e) {
            super.onLongPress(e);
            startAndPause();
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (isFullScreen) {
                setVideType(DEFAULT_SCREEN);
            } else {
                setVideType(FULL_SCREEN);
            }
            return super.onDoubleTap(e);
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (isShowMediaController) {
                hideMediaController();
                handler.removeMessages(HIDE_MEDIACONTROLLER);
            } else {
                showMediaController();
                handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
            }
            return super.onSingleTapConfirmed(e);
        }
    });

    private final Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message message){
            super.handleMessage(message);
            switch (message.what){
                case PROGRESS:
                    //更新系统时间
                    binding.mediaController.tvSystemTime.setText(getSystemTime());

                    //得到当前的播放进度
                    int currentPosition = binding.videoView.getCurrentPosition();
                    //更新视频进度条
                    binding.mediaController.seekbarVideo.setProgress(currentPosition);
                    //更新当前视频时长
                    binding.mediaController.tvCurrentTime.setText(Utils.stringForTime(currentPosition));

                    //设置缓冲效果
                    if (isNetUri) {
                        int buffer = binding.videoView.getBufferPercentage();//0~100;
                        int totalBuffer = binding.mediaController.seekbarVideo.getMax() * buffer;
                        int secondaryProgress = totalBuffer / 100;
                        binding.mediaController.seekbarVideo.setSecondaryProgress(secondaryProgress);
                    } else {
                        binding.mediaController.seekbarVideo.setSecondaryProgress(0);
                    }


                    int buffer = currentPosition - prePosition;
                    if(binding.videoView.isPlaying() && isNetUri && (duration - currentPosition) > 500){
                        if(buffer < 500){
                            binding.llBuffer.layoutBuffer.setVisibility(View.VISIBLE);
                        }else{
                            binding.llBuffer.layoutBuffer.setVisibility(View.GONE);
                        }
                    }

                    prePosition = currentPosition;

                    //每一秒更新一次
                    removeMessages(PROGRESS);
                    sendEmptyMessageDelayed(PROGRESS, 1000);
                    break;
                case HIDE_MEDIACONTROLLER://隐藏控制面板
                    hideMediaController();
                    break;
                case SHOW_SPEED:
                    String netSpeed = Utils.getNetSpeed(VideoPlayerActivity.this);
                    binding.llBuffer.tvBufferNetspeed.setText("缓存中.."+netSpeed);
                    binding.rlLoading.tvLoadingNetspeed.setText("正在玩命加载中..."+netSpeed);
                    handler.sendEmptyMessageDelayed(SHOW_SPEED,1000);
                    break;
            }
        }
    };

    @Override
    protected View getLayout() {
        binding = ActivityVideoPlayerBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void initView(){
        //开始暂停
        binding.mediaController.btnVideoStartPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAndPause();
            }
        });

        //静音开关
        binding.mediaController.btnVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isMute = !isMute;
                if(isMute){
                    updateVolume(0);
                }
                else {
                    updateVolume(currentVolume);
                }

                handler.removeMessages(HIDE_MEDIACONTROLLER);
                handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
            }
        });

        //调节音量
        binding.mediaController.seekbarVoice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    updateVolume(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                handler.removeMessages(HIDE_MEDIACONTROLLER);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
            }
        });

        //下一个
        binding.mediaController.btnVideoNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                position++;
                setPlayNextOrPre();
                handler.removeMessages(HIDE_MEDIACONTROLLER);
                handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
            }
        });

        //上一个
        binding.mediaController.btnVideoPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                position--;
                setPlayNextOrPre();
                handler.removeMessages(HIDE_MEDIACONTROLLER);
                handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
            }
        });

        //
        binding.mediaController.btnSwitchPlayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.removeMessages(HIDE_MEDIACONTROLLER);
                handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
            }
        });

        //拖放视频进度条
        binding.mediaController.seekbarVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    binding.videoView.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                handler.removeMessages(HIDE_MEDIACONTROLLER);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
            }
        });

        //切换全屏
        binding.mediaController.btnVideoSwitchScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFullScreen) {
                    setVideType(DEFAULT_SCREEN);
                } else {
                    setVideType(FULL_SCREEN);
                }
                handler.removeMessages(HIDE_MEDIACONTROLLER);
                handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
            }
        });

        initVideoView();
    }

    private void initVideoView(){
        binding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoWidth = mp.getVideoWidth();
                videoHeight = mp.getVideoHeight();

                initVideoInfo();

                handler.sendEmptyMessage(PROGRESS);

                mp.setLooping(true);
                binding.videoView.start();

                setVideType(DEFAULT_SCREEN);
                //隐藏加载页面
                binding.rlLoading.layoutLoading.setVisibility(View.GONE);
                handler.removeMessages(SHOW_SPEED);
            }
        });

        binding.videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                showErrorDialog();
                //Toast.makeText(VideoPlayerActivity.this,"播放出错了",Toast.LENGTH_LONG).show();
                return true;
            }
        });

        binding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if(mediaItems != null && !mediaItems.isEmpty()){
                    position++;
                    if(position < mediaItems.size()){
                        setPlayNextOrPre();
                    }
                    else{
                        Toast.makeText(VideoPlayerActivity.this,"已是最后一个视频了",Toast.LENGTH_LONG).show();
                        finish();
                    }
                }

            }
        });
    }

    public void initData(){
        initMediaData();
        //实例化AudioManager
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        //得到屏幕的高和宽
//        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
//        screenWidth = wm.getDefaultDisplay().getWidth();
//        screenHeight = wm.getDefaultDisplay().getHeight();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        screenWidth = displayMetrics.widthPixels;
        screenHeight = displayMetrics.heightPixels;

        hideMediaController();

        binding.mediaController.seekbarVoice.setMax(maxVolume);
        binding.mediaController.seekbarVoice.setProgress(currentVolume);

        //注册接收监听电量广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);

        //接收电量广播
        batteryReceiver = new BatteryReceiver(this);
        registerReceiver(batteryReceiver,intentFilter);

        //显示网速
        handler.sendEmptyMessage(SHOW_SPEED);

        //不锁屏
        binding.videoView.setKeepScreenOn(true);
    }

    private void initMediaData() {
        //初始化播放数据
        uri = getIntent().getData();//得到一个地址：文件浏览器，浏览器，相册
        mediaItems = (ArrayList<MediaItem>) getIntent().getSerializableExtra("videolist");
        //列表中的位置
        position = getIntent().getIntExtra("position",0);

        if(mediaItems != null && !mediaItems.isEmpty()){
            MediaItem mediaItem = mediaItems.get(position);
            binding.videoView.setVideoPath(mediaItem.getData());
            binding.mediaController.tvName.setText(mediaItem.getName());
            isNetUri = Utils.isNetUri(mediaItem.getData());
        }else if(uri != null){
            binding.videoView.setVideoURI(uri);
            binding.mediaController.tvName.setText(uri.toString());
            isNetUri = Utils.isNetUri(uri.toString());
        }
        setButtonState();
    }

    /**
     * 初始化视频需要显示的信息
     */
    private void initVideoInfo(){
        //视频总时长
        duration = binding.videoView.getDuration();
        binding.mediaController.tvDuration.setText(Utils.stringForTime(duration));
        binding.mediaController.seekbarVideo.setMax(duration);
    }

    private void setPlayNextOrPre() {
        MediaItem mediaItem = mediaItems.get(position);
        binding.videoView.setVideoPath(mediaItem.getData());
        binding.mediaController.tvName.setText(mediaItem.getName());
        isNetUri = Utils.isNetUri(mediaItem.getData());

        setButtonState();

        binding.rlLoading.layoutLoading.setVisibility(View.VISIBLE);
    }

    /**
     * 是否隐藏控制面板
     * true:显示
     * false:隐藏
     */
    private void hideMediaController() {
        binding.mediaController.llBottom.setVisibility(View.GONE);
        binding.mediaController.llTop.setVisibility(View.GONE);
        isShowMediaController = false;
    }

    private void showMediaController() {
        binding.mediaController.llBottom.setVisibility(View.VISIBLE);
        binding.mediaController.llTop.setVisibility(View.VISIBLE);
        isShowMediaController = true;
    }

    private void setVideType(int type) {
        switch (type) {
            case FULL_SCREEN://全屏
                binding.videoView.setVideoSize(screenWidth, screenHeight);
                isFullScreen = true;

                binding.mediaController.btnVideoSwitchScreen.setBackgroundResource(R.drawable.btn_switch_screen_default_selector);
                break;
            case DEFAULT_SCREEN://默认
                //真实视频的高和宽
                int mVideoWidth = videoWidth;
                int mVideoHeight = videoHeight;
                int width = screenWidth;
                int height = screenHeight;
                if (mVideoWidth > 0 && mVideoHeight > 0) {
                    // for compatibility, we adjust size based on aspect ratio
                    if (mVideoWidth * height < width * mVideoHeight) {
                        width = height * mVideoWidth / mVideoHeight;
                    } else if (mVideoWidth * height > width * mVideoHeight) {
                        height = width * mVideoHeight / mVideoWidth;
                    }
                    binding.videoView.setVideoSize(width, height);
                }
                isFullScreen = false;
                binding.mediaController.btnVideoSwitchScreen.setBackgroundResource(R.drawable.btn_switch_screen_full_selector);
                break;
        }
    }

    /**
     * 根据传入的值修改音量
     *
     * @param volume
     */
    private void updateVolume(int volume) {
        if (volume <= 0) {
            isMute = true;
        } else {
            isMute = false;
        }

        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
        binding.mediaController.seekbarVoice.setProgress(volume);//设置seekBar进度
        if(!isMute){
            currentVolume = volume;
        }
    }

    /**
     * 开始暂停播放
     */
    private void startAndPause() {
        if (binding.videoView.isPlaying()) {
            //暂停
            binding.videoView.pause();
            //按钮设置播放状态
            binding.mediaController.btnVideoStartPause.setBackgroundResource(R.drawable.btn_video_play_selector);
        } else {
            //播放
            binding.videoView.start();
            //按钮设置暂停状态
            binding.mediaController.btnVideoStartPause.setBackgroundResource(R.drawable.btn_video_pause_selector);
        }
        handler.removeMessages(HIDE_MEDIACONTROLLER);
        handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
    }

    /**
     * 设置上一个和下一个按钮的状态
     */
    private void setButtonState() {
        //播放列表
        if (mediaItems != null && !mediaItems.isEmpty()) {
            if(position == 0 && mediaItems.size() == 1){
                binding.mediaController.btnVideoNext.setEnabled(false);
                binding.mediaController.btnVideoNext.setBackgroundResource(R.mipmap.btn_next_gray);
                binding.mediaController.btnVideoPre.setEnabled(false);
                binding.mediaController.btnVideoPre.setBackgroundResource(R.mipmap.btn_pre_gray);
            }
            else if (position == 0) {//第一个视频
                binding.mediaController.btnVideoPre.setEnabled(false);
                binding.mediaController.btnVideoPre.setBackgroundResource(R.mipmap.btn_pre_gray);
            } else if (position == mediaItems.size() - 1) {//最后一个视频
                binding.mediaController.btnVideoNext.setEnabled(false);
                binding.mediaController.btnVideoNext.setBackgroundResource(R.mipmap.btn_next_gray);
            } else {
                binding.mediaController.btnVideoNext.setEnabled(true);
                binding.mediaController.btnVideoNext.setBackgroundResource(R.drawable.btn_video_next_selector);
                binding.mediaController.btnVideoPre.setEnabled(true);
                binding.mediaController.btnVideoPre.setBackgroundResource(R.drawable.btn_video_pre_selector);
            }

        } else if (uri != null) {
            binding.mediaController.btnVideoNext.setEnabled(false);
            binding.mediaController.btnVideoNext.setBackgroundResource(R.mipmap.btn_next_gray);
            binding.mediaController.btnVideoPre.setEnabled(false);
            binding.mediaController.btnVideoPre.setBackgroundResource(R.mipmap.btn_pre_gray);
        } else {
            Toast.makeText(this, "没有播放地址", Toast.LENGTH_SHORT).show();
        }

    }

    public void setBattery(int level) {
        if(level<=0){
            binding.mediaController.ivBattery.setImageResource(R.mipmap.ic_battery_0);
        }else if(level <=10){
            binding.mediaController.ivBattery.setImageResource(R.mipmap.ic_battery_10);
        }else if(level <=20){
            binding.mediaController.ivBattery.setImageResource(R.mipmap.ic_battery_20);
        }else if(level <=40){
            binding.mediaController.ivBattery.setImageResource(R.mipmap.ic_battery_40);
        }else if(level <=60){
            binding.mediaController.ivBattery.setImageResource(R.mipmap.ic_battery_60);
        }else if(level <=80){
            binding.mediaController.ivBattery.setImageResource(R.mipmap.ic_battery_80);
        }else if(level <=100){
            binding.mediaController.ivBattery.setImageResource(R.mipmap.ic_battery_100);
        }else{
            binding.mediaController.ivBattery.setImageResource(R.mipmap.ic_battery_100);
        }
    }

    @Override
    protected void onDestroy(){
        if(batteryReceiver != null){
            unregisterReceiver(batteryReceiver);
            batteryReceiver = null;
        }
        super.onDestroy();
    }

    /**
     * 得到系统时间
     */
    private String getSystemTime() {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        return format.format(new Date());
    }

    private void showErrorDialog() {
        new AlertDialog.Builder(this).setTitle("提示").setMessage("播放视频出错了，请检查网络或者视频是否有缺损！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //把事件给手势识别器解析
        detector.onTouchEvent(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = event.getX();
                startY = event.getY();
                touchRang = Math.min(screenHeight, screenWidth);
                mVol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                handler.removeMessages(HIDE_MEDIACONTROLLER);
                break;
            case MotionEvent.ACTION_MOVE:
                float endY = event.getY();
                float endX = event.getX();

                if(endX < screenWidth/2){
                    //左边-滑动改变屏幕的亮度
                    final double FLING_MIN_DISTANCE = 0.5;
                    final double FLING_MIN_VELOCITY = 0.5;
                    if (startY - endY > FLING_MIN_DISTANCE && Math.abs(endY-startY) > FLING_MIN_VELOCITY) {
                        setBrightness(20);
                    }
                    if (startY - endY < FLING_MIN_DISTANCE && Math.abs(endY-startY) > FLING_MIN_VELOCITY) {
                        setBrightness(-20);
                    }

                }else{
                    //-右边-滑动改变声音
                    //计算偏移量
                    float distanceY = startY - endY;
                    //屏幕滑动的距离： 总距离 = 改变的声音： 最大音量
                    float changVolume = (distanceY / touchRang) * maxVolume;

                    //最终的声音= 原来的音量 + 改变的声音；
                    float volume = Math.min(Math.max(mVol + changVolume, 0), maxVolume);


                    if (changVolume != 0) {
                        updateVolume((int) volume);
                    }

                }
                break;
            case MotionEvent.ACTION_UP:
                handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            currentVolume--;
            updateVolume(currentVolume);
            handler.removeMessages(HIDE_MEDIACONTROLLER);
            handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
            //返回true不让系统的音量大小进入条弹出来
            return  true;
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            currentVolume++;
            updateVolume(currentVolume);
            handler.removeMessages(HIDE_MEDIACONTROLLER);
            handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROLLER, 5000);
            return  true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /*
     *
     * 设置屏幕亮度 lp = 0 全暗 ，lp= -1,根据系统设置， lp = 1; 最亮
     */
    public void setBrightness(float brightness) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        // if (lp.screenBrightness <= 0.1) {
        // return;
        // }
        lp.screenBrightness = lp.screenBrightness + brightness / 255.0f;
        /**
         * 震动
         */
        Vibrator vibrator;
        if (lp.screenBrightness > 1) {
            lp.screenBrightness = 1;
            vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            long[] pattern = { 10, 200 }; // OFF/ON/OFF/ON...
            vibrator.vibrate(pattern, -1);
        } else if (lp.screenBrightness < 0.2) {
            lp.screenBrightness = (float) 0.2;
            vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            long[] pattern = { 10, 200 }; // OFF/ON/OFF/ON...
            vibrator.vibrate(pattern, -1);
        }
        Log.e("screenBrightness", "lp.screenBrightness= " + lp.screenBrightness);
        getWindow().setAttributes(lp);
    }

}

